/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.core.sensitive;

import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie;
import java.util.ArrayList;
import java.util.List;
import org.elsfs.cloud.common.core.sensitive.wordsource.ISensitiveWordSource;
import org.elsfs.cloud.common.core.sensitive.wordsource.SensitiveWordSourceFromResource;

/**
 * 默认处理器
 *
 * @author zeng
 */
public class SensitiveWordProvider implements ISensitiveWordProvider {
  private final ISensitiveWordSource source;

  /** 构造器 */
  public SensitiveWordProvider() {
    // 默认从resource目录下读取sensitive.txt文件
    this.source = new SensitiveWordSourceFromResource();
  }

  /**
   * 构造器
   *
   * @param sensitiveWordSource 敏感词数据源
   */
  public SensitiveWordProvider(ISensitiveWordSource sensitiveWordSource) {
    this.source = sensitiveWordSource;
  }

  /** 刷新词库 */
  public void reload() {
    SensitiveDictionary.reload(source::loadSource);
  }

  @Override
  public String handle(String word, String symbol) {
    List<AhoCorasickDoubleArrayTrie.Hit<String>> hits =
        SensitiveDictionary.handle(source::loadSource, word);
    if (hits.isEmpty()) {
      return word;
    }
    StringBuilder buffer = new StringBuilder(word);
    for (AhoCorasickDoubleArrayTrie.Hit<String> hit : hits) {
      buffer.replace(hit.begin, hit.end, symbol.repeat(hit.value.length()));
    }
    return buffer.toString();
  }

  @Override
  public List<String> contain(String word) {
    List<String> list = new ArrayList<>();
    List<AhoCorasickDoubleArrayTrie.Hit<String>> hits =
        SensitiveDictionary.handle(source::loadSource, word);
    for (AhoCorasickDoubleArrayTrie.Hit<String> hit : hits) {
      String sensitive = hit.value.trim();
      if (!list.contains(sensitive)) {
        list.add(sensitive);
      }
    }
    return list;
  }
}
